package vista;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;

import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;

import javax.swing.JOptionPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.LayoutStyle;
import javax.swing.SwingConstants;

import sistema.Sistema;
import vista.verificaciones.VerificarEntrada;


/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
/**
* Panel que nos permitira  ingresar una MEDICION
 * a el USUARIO RESIDENCIAL
*/
public class PanelUResidencialFactura extends javax.swing.JPanel implements ActionListener {
	private static final long serialVersionUID = 1L;
	private JLabel lblTitulo;
	private JLabel lblNroUsuario;
	private JTextField txtCuit;
	private JLabel lblFacturaDisp;
	private JButton btnCancelar;
	private JComboBox cmbFactDisp;
	private JButton btnAceptar;
	private JButton btnBuscar;
	
	//Este es frame que contiene al Panel. Se agrega para ocultarlo
	protected JFrame frame;
	private Sistema sistema;
//Comandos para los Action
	
	private static String CMD_BUSCAR="cmd_buscar";
	private static String CMD_ACEPTAR="cmd_aceptar";
	private static String CMD_CANCELAR="cmd_cancelar";

//Constructor
	public PanelUResidencialFactura(JFrame frame) {
		super();
		
		//Guardamos el frame que contiene al panel. Cuando aprete cancelar, 
		//se oculta la ventana
		this.frame=frame;
		this.sistema = Sistema.getInstancia();
		initGUI();
		this.btnAceptar.setEnabled(false);
	}
	
	private void initGUI() {
		try {
			GroupLayout thisLayout = new GroupLayout((JComponent)this);
			this.setLayout(thisLayout);
			this.setPreferredSize(new java.awt.Dimension(400, 203));
			{
				lblTitulo = new JLabel();
				lblTitulo.setText("USUARIO RESIDENCIAL-FACTURAS DISPONIBLES");
				lblTitulo.setHorizontalAlignment(SwingConstants.CENTER);
			}
			{
				//TENGO Q VER COMO CARGAR LAS FACTURAS DISPONIBLE DEL USUARIO
				ComboBoxModel cmbFactDispModel = 
						new DefaultComboBoxModel(
								new String[] { "Item One", "Item Two" });
				cmbFactDisp = new JComboBox();
				cmbFactDisp.setModel(cmbFactDispModel);
			}
			{
				btnBuscar = new JButton();
				btnBuscar.setText("BUSCAR");
				btnBuscar.addActionListener(this);
				btnBuscar.setActionCommand(CMD_BUSCAR);
			}
			{
				lblFacturaDisp = new JLabel();
				lblFacturaDisp.setText("Facturas Disponibles");
			}
			{
				btnAceptar = new JButton();
				btnAceptar.setText("ACEPTAR");
				btnAceptar.setActionCommand(CMD_ACEPTAR);
				btnAceptar.addActionListener(this);
			}
			{
				btnCancelar = new JButton();
				btnCancelar.setText("CANCELAR");
				btnCancelar.setActionCommand(CMD_CANCELAR);
				btnCancelar.addActionListener(this);
			}
			
			{
				lblNroUsuario = new JLabel();
				lblNroUsuario.setText("Nro Usuario");
			}
			{
				txtCuit = new JTextField();
			}
			thisLayout.setVerticalGroup(thisLayout.createSequentialGroup()
				.addContainerGap()
				.addComponent(lblTitulo, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)
				.addGap(27)
				.addGroup(thisLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
				    .addComponent(btnBuscar, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, 22, GroupLayout.PREFERRED_SIZE)
				    .addComponent(lblNroUsuario, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)
				    .addComponent(txtCuit, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, 19, GroupLayout.PREFERRED_SIZE))
				.addGap(26)
				.addGroup(thisLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
				    .addComponent(cmbFactDisp, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)
				    .addComponent(lblFacturaDisp, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, 16, GroupLayout.PREFERRED_SIZE))
				.addGap(24)
				.addGroup(thisLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
				    .addComponent(btnAceptar, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, 22, GroupLayout.PREFERRED_SIZE)
				    .addComponent(btnCancelar, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, 22, GroupLayout.PREFERRED_SIZE))
				.addContainerGap(31, 31));
			thisLayout.setHorizontalGroup(thisLayout.createSequentialGroup()
				.addContainerGap(17, 17)
				.addGroup(thisLayout.createParallelGroup()
				    .addGroup(GroupLayout.Alignment.LEADING, thisLayout.createSequentialGroup()
				        .addGroup(thisLayout.createParallelGroup()
				            .addComponent(lblFacturaDisp, GroupLayout.Alignment.LEADING, 0, 127, Short.MAX_VALUE)
				            .addGroup(GroupLayout.Alignment.LEADING, thisLayout.createSequentialGroup()
				                .addComponent(lblNroUsuario, GroupLayout.PREFERRED_SIZE, 85, GroupLayout.PREFERRED_SIZE)
				                .addGap(42)))
				        .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
				        .addGroup(thisLayout.createParallelGroup()
				            .addComponent(cmbFactDisp, GroupLayout.Alignment.LEADING, GroupLayout.PREFERRED_SIZE, 117, GroupLayout.PREFERRED_SIZE)
				            .addGroup(thisLayout.createSequentialGroup()
				                .addGap(0, 0, Short.MAX_VALUE)
				                .addComponent(txtCuit, GroupLayout.PREFERRED_SIZE, 117, GroupLayout.PREFERRED_SIZE)))
				        .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, 0, GroupLayout.PREFERRED_SIZE)
				        .addComponent(btnBuscar, GroupLayout.PREFERRED_SIZE, 85, GroupLayout.PREFERRED_SIZE))
				    .addGroup(thisLayout.createSequentialGroup()
				        .addGap(7)
				        .addGroup(thisLayout.createParallelGroup()
				            .addGroup(thisLayout.createSequentialGroup()
				                .addComponent(lblTitulo, GroupLayout.PREFERRED_SIZE, 340, GroupLayout.PREFERRED_SIZE)
				                .addGap(0, 0, Short.MAX_VALUE))
				            .addGroup(GroupLayout.Alignment.LEADING, thisLayout.createSequentialGroup()
				                .addGap(43)
				                .addComponent(btnAceptar, GroupLayout.PREFERRED_SIZE, 98, GroupLayout.PREFERRED_SIZE)
				                .addGap(46)
				                .addComponent(btnCancelar, GroupLayout.PREFERRED_SIZE, 104, GroupLayout.PREFERRED_SIZE)
				                .addGap(0, 49, Short.MAX_VALUE)))
				        .addGap(6)))
				.addContainerGap(30, 30));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	//Getter y Setter 
	public String getTxtCuit() {
		return txtCuit.getText();
	}

	public void setTxtNroUsuario(String nro) {
		this.txtCuit.setText(nro);
	}
	
	
	public String getCmbFactDisp() {
		return (String) cmbFactDisp.getSelectedItem();
	}

	//OJO ESTO NO ES ASI!!!!!!!!!!!
	public void setCmbFactDisp(String cmbFactDisp) {
		this.cmbFactDisp.setSelectedItem(cmbFactDisp);
	}

	/**
	 * Verifica que se haya ingresado un dato
	 * @return true or false
	 */
	
	private boolean verificacion_entrada(){
		
		 String mensaje ="DEBE INGRESAR:";
		
		//Creo el objeto para la validacion
		VerificarEntrada verificar = new VerificarEntrada();
		
		if (!verificar.verificarVacios(this.txtCuit.getText())){
			JOptionPane.showMessageDialog(null, "NUMERO DE USUARIO RESIDENCIAL", mensaje,JOptionPane.ERROR_MESSAGE );
           return false;
		}
		
		return true;
	}	

		
	
	@Override
	public void actionPerformed(ActionEvent arg0) {
		
		if (CMD_BUSCAR.equals(arg0.getActionCommand())){
			
			//Verifico que haya ingresado un Nro de Usuario
			
			if (verificacion_entrada()){
				//Busco al USUARIO
				
				DatosUsuario datosUsuario=Sistema.getInstancia().datosUR(this.getNroUsuario());	
				if (datosUsuario != null){
					cargarDatos(datosUsuario);
				} 
				else {
					this.mostrarUsuarioInexistente();
				}
				
				//Cargo el ComboBox con las facturas
				//Si encontro Hacer Visible el boton Aceptar
				this.btnAceptar.setEnabled(true);
			}
		}
		
		else if (CMD_ACEPTAR.equals(arg0.getActionCommand())){
			
		}
		else if (CMD_CANCELAR.equals(arg0.getActionCommand())){
			this.frame.dispose();
		}
		
	}

	/**
	 * Muestra un mensaje informando que el usuario no existe
	 */
	protected void mostrarUsuarioInexistente() {
		String mensaje = "El usuario con nro: " + this.txtCuit.getText() + "\n " +
						 "no existe.";
		String titulo = "Usuario Industrial Inexistente";
		
		//Muestra el mensaje
		JOptionPane.showMessageDialog(null, mensaje, titulo, JOptionPane.ERROR_MESSAGE);
		
	}
	private void cargarDatos(DatosUsuario datosUsuario) {
		// TODO Auto-generated method stub
		
	}

	/**
	 * Devuelve el numero del usuario
	 * @return
	 */
	private int getNroUsuario() {
		String nro = this.txtCuit.getText();
		int numero = -1;
		if (nro != null && !nro.isEmpty()){
			try {
				numero = Integer.parseInt(nro);
			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				numero = -1;
				e.printStackTrace();
			}
		}
		// TODO Auto-generated method stub
		return numero;
	}

}
